import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/components/button_components/base_button.dart';

import 'base_select_hours_and_minutes.dart';

/// 这是选择预约时间的组件
/// 镶嵌在BaseComponentUtils.openSelectAppointmentTime方法调去的弹窗里
class BaseAppointmentTime extends StatefulWidget {
  /// 默认选择区域
  final String appointmentArea;

  /// 默认选择的时间段
  final DateTime appointmentTime;

  /// 外界传入的快递公司编号
  final String logisticsCode;

  /// 选择后将已选数据回调的方法
  final Function(DateTime time, String area) onChange;

  const BaseAppointmentTime({Key key, this.appointmentArea = '', this.appointmentTime, @required this.onChange, this.logisticsCode}) : super(key: key);

  @override
  _BaseAppointmentTimeState createState() => _BaseAppointmentTimeState();
}

class _BaseAppointmentTimeState extends State<BaseAppointmentTime> {
  /// 日期
  final List<DateTime> _dateDateTime = [];
  final List<String> _dateString = ["今天", "明天"];

  ///时间段
  List<String> get _period => (widget.logisticsCode == "SFSDT" || widget.logisticsCode == "SFTC") ? List<String>.generate(29, (index) => "${8 + (index % 2 == 0 ? index / 2 : (index - 1) / 2).toInt()}:${index % 2 == 0 ? '00' : '30'}") : List<String>.generate(6, (index) => "${8 + index * 2}:00~${8 + index * 2 + 2}:00");

  int _dateIndex = 0;

  int _periodIndex = 0;

  /// 预约时间段（时间段）
  String _appointmentArea = "";

  /// 预约时间（年月日）
  DateTime _appointmentTime;

  /// 初始化方法
  /// 根据默认参数，初始化内部属性
  @override
  void initState() {
    super.initState();
    _dateDateTime.clear();
    DateTime _now = DateTime.now();
    _dateString.asMap().keys.forEach((index) {
      _dateDateTime.add(DateTime(_now.year, _now.month, _now.day).add(Duration(days: index)));
    });
    _dateIndex = 0;
    _periodIndex = 0;
    if (widget.appointmentArea.isNotEmpty) _appointmentArea = widget.appointmentArea;
    int _periodSelectIndex = _period.indexWhere((element) => element == _appointmentArea);
    if (_periodSelectIndex != -1) _periodIndex = _periodSelectIndex;
    if (widget.appointmentTime != null) {
      _appointmentTime = widget.appointmentTime;
    }
    int _dateSelectIndex = -1;
    if (_appointmentTime != null) {
      _dateSelectIndex = _dateDateTime.indexWhere((element) => element.year == _appointmentTime.year && element.month == _appointmentTime.month && element.day == _appointmentTime.day);
    }
    if (_dateSelectIndex != -1) _dateIndex = _dateSelectIndex;
  }

  /// 构建页面
  @override
  Widget build(BuildContext context) {
    return Container(
      height: double.infinity,
      width: double.infinity,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(flex: 25, child: _buildDateWidget()),
          Expanded(flex: 75, child: _buildPeriodWidget()),
        ],
      ),
    );
  }

  /// 日期模块
  Widget _buildDateWidget() {
    return Container(
      height: double.infinity,
      color: Color(0xFFF3F3F3),
      child: ListView.builder(
        shrinkWrap: true,
        itemCount: _dateString.length,
        itemBuilder: (BuildContext context, int index) {
          return InkWell(
            onTap: () => _dateWidgetEvent(index),
            child: Container(
              height: 48,
              alignment: Alignment.center,
              color: _dateIndex == index ? Colors.white : Color(0xFFF3F3F3),
              child: Text(_dateString[index], style: TextStyle(color: _dateIndex == index ? Color(0xffD9001B) : Color(0xFF333333))),
            ),
          );
        },
      ),
    );
  }

  ///时间模块
  Widget _buildPeriodWidget() {
    // if (widget.logisticsCode == "SFTC") {
    //   List<String> area = _appointmentArea.split(":");
    //   int initHours = 8;
    //   if (area.length == 2 && area[0] != null) initHours = BaseDefaultsValue.intDefaults(area[0]);
    //   int initMinutes = 0;
    //   if (area.length == 2 && area[1] != null) initMinutes = BaseDefaultsValue.intDefaults(area[1]);
    //   return Column(
    //     children: [
    //       Expanded(flex: 8, child: BaseSelectHoursAndMinutes(hours: initHours, minutes: initMinutes, selected: _onSelectHoursAndMinutesEvent)),
    //       Expanded(flex: 2, child: _buildOkButton()),
    //     ],
    //   );
    // }
    return Container(
      height: double.infinity,
      child: ListView.builder(
        shrinkWrap: true,
        itemCount: _period.length,
        itemBuilder: (BuildContext context, int index) {
          return InkWell(
            onTap: () => _periodWidgetEvent(index),
            child: Container(
              height: 48,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 24),
              color: _periodIndex == index ? Color(0xffD9001B).withOpacity(0.05) : Colors.white,
              child: Text(_period[index], style: TextStyle(color: _periodIndex == index ? Color(0xffD9001B) : Color(0xFF333333))),
            ),
          );
        },
      ),
    );
  }

  /// 确定按钮
  Widget _buildOkButton() {
    return Column(
      children: [
        BaseButton(text: '确定', onPress: () => _outPut(isOther: true)),
      ],
    );
  }

  /// 日期模块的日期选中事件
  void _dateWidgetEvent(int index) {
    if (_dateIndex == null || _dateIndex != index) {
      _dateIndex = index;
      _periodIndex = 0;
      setState(() {});
    }
  }

  void _onSelectHoursAndMinutesEvent(int hours, int minutes) {
    _appointmentArea = "${BaseTransformUtil.format(hours)}:${BaseTransformUtil.format(minutes)}";
  }

  /// 时间段模块，选中事件
  void _periodWidgetEvent(int index) {
    _periodIndex = index;
    _outPut();
    // 直接退出了。不用刷新了
    // setState(() {});
  }

  /// 处理出参
  void _outPut({bool isOther = false}) {
    if (widget.onChange != null) {
      if (isOther) widget.onChange(_dateDateTime[_dateIndex], _appointmentArea.isEmpty ? "08:00" : _appointmentArea);
      if (!isOther) widget.onChange(_dateDateTime[_dateIndex], _period[_periodIndex]);
    }
    BaseRouterUtil.getInstance().pop();
  }
}
